package easymodbus4j.example3.sl651;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class NettyTcpClient {
    private final String host;
    private final int port;
    private Channel channel;

    public NettyTcpClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    // 启动客户端并连接服务器
    public void start() throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true) // 禁用Nagle算法，减少延迟
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 使用UTF-8编码，解决中文乱码
                            pipeline.addLast(new StringDecoder(StandardCharsets.UTF_8));
                            pipeline.addLast(new StringEncoder(StandardCharsets.UTF_8));
                            // 添加自定义客户端处理器
                            pipeline.addLast(new TcpClientHandler());
                        }
                    });

            // 连接服务器
            ChannelFuture future = bootstrap.connect(host, port).sync();
            System.out.println("客户端已连接到服务器: " + host + ":" + port);

            // 保存通道引用，用于后续发送消息
            channel = future.channel();

            // 等待连接关闭
            future.channel().closeFuture().sync();
        } finally {
            // 优雅关闭
            group.shutdownGracefully();
        }
    }

    // 发送消息到服务器
    public void sendMessage(String message) {
        if (channel != null && channel.isActive()) {
            channel.writeAndFlush(message);
        } else {
            System.out.println("连接未建立或已断开，无法发送消息");
        }
    }

    // 自定义客户端处理器
    static class TcpClientHandler extends SimpleChannelInboundHandler<String> {

        // 连接成功时触发
        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            System.out.println("已成功连接到服务器");
        }

        // 接收服务器消息
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) {
            System.out.println("\n收到服务器消息: " + msg);
            System.out.print("请输入要发送的消息: ");
        }

        // 连接断开时触发
        @Override
        public void channelInactive(ChannelHandlerContext ctx) {
            System.out.println("与服务器的连接已断开");
        }

        // 发生异常时触发
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            System.out.println("发生异常: " + cause.getMessage());
            ctx.close();
        }
    }

    // 客户端入口
    public static void main(String[] args) {
        try {
            // 创建客户端并连接服务器
            NettyTcpClient client = new NettyTcpClient("127.0.0.1", 8886);

            // 启动客户端连接（单独线程，避免阻塞输入）
            new Thread(() -> {
                try {
                    client.start();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    System.out.println("客户端启动失败: " + e.getMessage());
                }
            }).start();

            // 等待连接建立（简单延迟，实际项目可使用更优雅的方式）
            Thread.sleep(1000);

            // 控制台输入消息并发送
            Scanner scanner = new Scanner(System.in);
            System.out.print("请输入要发送的消息（输入exit退出）: ");

            while (true) {
                String message = scanner.nextLine();

                // 退出条件
                if ("exit".equalsIgnoreCase(message)) {
                    System.out.println("客户端即将退出");
                    scanner.close();
                    System.exit(0);
                }

                // 发送消息
                client.sendMessage(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

